package com.tanhua.dubbo.api;

import cn.hutool.core.util.PageUtil;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: tanhua
 * @description:
 * @author: MR.peng
 * @create: 2022-03-29 15:31
 **/

@DubboService
public class videoApiImpl implements videoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存视频
    @Override
    public void save(Video video) {
        mongoTemplate.save(video);
    }

    //根据id集合查询
    /*
     * vids: 所有推荐视频的id集合
     *   1、如果redis数据足以分页，展示推荐的数据
     *   2、如果redis的数据不足以分页，查询所有
     *
     * */
    @Override
    public List<Video> findByIds(String[] vids, Integer page, Integer pagesize) {
        //redis中支持的最大页数
        int totalPage = PageUtil.totalPage(vids.length, pagesize);//数据总数，每页查询条数
        if(page <= totalPage){
            //根据id查询
            Criteria criteria = Criteria.where("id").in(vids);
            Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize);
             return  mongoTemplate.find(query,Video.class);
        }else {
            //查询所有,倒叙展示
            //如果超过最大则是从第一页开始查询
            return findAll(page-totalPage,pagesize);
        }
    }


    //查询所有
    @Override
    public List<Video> findAll(Integer page, Integer pagesize) {
        //没有查询条件
        Query query = new Query().with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        return mongoTemplate.find(query,Video.class);
    }


    //根据用户id分页查询用户发布的视频列表
    @Override
    public PageResult findByUserId(Long uid, Integer page, Integer pagesize) {
        //1.创建Criteria
        Criteria criteria = Criteria.where("userId").is(uid);
        //2.创建Query
        Query query = Query.query(criteria);
        //3.查询总数
        long count = mongoTemplate.count(query, Video.class);
        //4.设置分页参数
        query.with(Sort.by(Sort.Order.desc("created")))
                .limit(pagesize)
                .skip((page-1) * pagesize);
        //5.查询列表
        List<Video> list = mongoTemplate.find(query, Video.class);
        //6.返回
        return new  PageResult(page,pagesize,count,list);
    }

    //返回视频列表与总数
    @Override
    public Map findVideoComments(Integer page, Integer pageSize, String videoId) {

        Criteria criteria = Criteria.where("publishId").is(new ObjectId(videoId)).and("commentType").is(2);
        Query q = Query.query(criteria).skip((page - 1) * pageSize)
                .limit(pageSize)
                .with(Sort.by(Sort.Order.desc("created")));

        List<Comment> videoComments = mongoTemplate.find(q, Comment.class);
        System.out.println(videoComments.toString());


        Query q1 = Query.query(criteria);  //查询评论总数条件
        long count = mongoTemplate.count(q1, Comment.class);
        Map map = new HashMap();
        map.put("list", videoComments);
        map.put("count", count);
        return map;
    }


    @Override
    public Integer disLike(String videoId, Long userId) {
        Criteria criteria = Criteria.where("publishId").is(videoId).and("userId").is(userId).and("commentType").is(1);
        Query query = Query.query(criteria);
        mongoTemplate.remove(query, Comment.class);

        return returnNum(videoId, 1, -1);
    }
    //返回视频点赞或评论最新数据
    public Integer returnNum(String videoId, Integer type, Integer num) {
        Criteria criteria = Criteria.where("id").is(videoId);
        Query query = Query.query(criteria);
        Update update = new Update();
        if (1 == type) {
            update.inc("likeCount", num);
        } else if (2 == type) {
            update.inc("commentCount", num);
        }

        FindAndModifyOptions f = new FindAndModifyOptions();
        f.returnNew(true);
        Video newVideo = mongoTemplate.findAndModify(query, update, f, Video.class);

        if (1 == type) {
            return newVideo.getLikeCount();
        } else {
            return newVideo.getCommentCount();
        }

    }

    //视频点赞或评论处理
    @Override
    public Integer videoCommentHandle(String videoId, Long handleId, Integer type, String txt) {
        Criteria criteria = Criteria.where("id").is(new ObjectId(videoId));
        Query query = Query.query(criteria);
        Video video = mongoTemplate.findOne(query, Video.class);
        System.out.println("获取到的video：！！！！"+video);
        Comment videoComment = new Comment();
        videoComment.setCommentType(type);
        videoComment.setUserId(handleId);
        videoComment.setPublishUserId(video.getUserId());
        videoComment.setCreated(System.currentTimeMillis());
        videoComment.setPublishId(new ObjectId(videoId));

        if (1 == type) {
            mongoTemplate.save(videoComment);
            System.out.println(videoComment);
            return returnNum(videoId, type, 1);
        } else {
            if (StringUtils.isEmpty(txt)) {
                throw new RuntimeException("评论为空");
            }
            videoComment.setContent(txt);
            mongoTemplate.save(videoComment);
            System.out.println(videoComment);
            return returnNum(videoId, type, 1);
        }
    }
}
